--swimtab super early beta!

VERSION = "0.6"
--this is coming soon
SwimCloth =  AceLibrary("AceAddon-2.0"):new("AceConsole-2.0", "AceEvent-2.0","AceDB-2.0","FuBarPlugin-2.0")
local L = AceLibrary("AceLocale-2.2"):new("SwimCloth")
SwimCloth:RegisterDB("SwimClothDB","SwimClothDBPerChar")
SwimCloth:RegisterDefaults("profile", {
	enable = true,
	quickquest = false,
	avnumber = 0,
})

SCOptions = {
	type = 'group',
	args = {
		quickquest = {
			type = 'toggle',
			name = 'quickquest',
			desc = 'Speeds up quest turnins.',
			get = function()
				return SwimCloth.db.profile.quickquest
				end,
			set = function(v)
				value = v
				end,
			map = {
				[false] = "Slow", [true] = "Fast"
			},
		},
		AV = {
			type = 'group',
			name = 'avoptions',
			desc = 'AV Options',
			args = {
				joinav = {
					type = 'execute',
					name = 'joinav',
					desc = 'Increases your chances of getting a raid to join AV',
					func = "sendMessage",
				},
				AVNumber = {
					type = 'range',
					name = 'AVNumber',
					desc = 'Which Battle ground you want to queue, 0 for the first available',
					get = function()
						return SwimCloth.db.profile.avnumber
					end,
					set = function(v)
						SwimCloth.db.profile.avnumber = v
					end,
					min = 0,
					max = 10,
					step = 1,
					isPercent = false,
				},	
			},
		},
		cloth = {
			type = 'execute',
			name = 'howmuch',
			desc = 'Returns the amount of runecloth and how many stacks you have',
			func = function()
				local runeammount = SwimCloth:GetItemCount(L["Runecloth"])
				SwimCloth:Print(runeammount, " runecloth.")
				stacks = runeammount / 20
					SwimCloth:Print(stacks, " stacks.")
				
			end,
		},
		versionquery = {
			type = 'execute',
			name = 'versionquery',
			desc = 'Query\'s the raid for the version of swimcloth they are running',
			func = function()
					if (IsRaidLeader()) then
						SendAddonMessage("SwimCloth","whatversion","RAID")
					else
						SwimCoth:Print("You must be raid leader to preform this function.")
					end
			end,
		}
	}
}


SwimCloth.OnMenuRequest = SCOptions;
local tablet = AceLibrary("Tablet-2.0")
function SwimCloth:OnTooltipUpdate()
	local cat = tablet:AddCategory(
    'text', "Faction",
	'text2', "How much",
    'columns', 3,
    'child_textR', 1,
    'child_textG', 1,
    'child_textB', 0,
    'child_textR2', 1,
    'child_textG2', 1,
    'child_textB2', 1
	)
	for factionIndex = 1, GetNumFactions() do
  		name, description, standingId, bottomValue, topValue, earnedValue, atWarWith,
  		canToggleAtWar, isHeader, isCollapsed, isWatched = GetFactionInfo(factionIndex)

		if isHeader == nil then
			rep =  earnedValue .. "/" .. topValue
			cat:AddLine (
	  		'text',  name,
  			'text2', rep)
  		elseif isHeader then
			cat:AddLine ('text',name,'textR',1,'textG',0,'textB',1)
		end
	end
end

SwimCloth:RegisterChatCommand({"/swimcloth","/sc"},SCOptions)
function SwimCloth:OnEnable()
	self:RegisterEvent("GOSSIP_SHOW","OnGossipShow")
	self:RegisterEvent("QUEST_PROGRESS","OnQuestProgress")
	self:RegisterEvent("QUEST_COMPLETE","OnQuestComplete")
	self:RegisterEvent("UPDATE_FACTION","UpdateTooltip")
	self:RegisterEvent("BAG_UPDATE","UpdateText")
	self:RegisterEvent("CHAT_MSG_ADDON","OnMsgRsv")
--	self:RegisterEvent("BANKFRAME_OPENED","UpdateBankCloth")
--	self:RegisterEvent("BANKFRAME_CLOSED","CloseBank")
end

function SwimCloth:UpdateBankCloth()
	self:Print("Bank Opened")
	ItemName = L["Runecloth"]
	local anzl, bagNr, bagSlot = 0
	for bagNr = -1, 10, 1 do
		for bagSlot = 1, GetContainerNumSlots(bagNr), 1 do
			if (SwimCloth:GetItemName(bagNr, bagSlot) == ItemName) then
				local _, itemCount = GetContainerItemInfo(bagNr, bagSlot)
				anzl = anzl+itemCount;
			end
		end
	end
	self:Print(anzl);
end

--function SwimCloth:CloseBank()
--	self:Print("Bank Closed")
--end
function SwimCloth:OnTextUpdate()
	local runeammount = SwimCloth:GetItemCount(L["Runecloth"])
	stacks = runeammount / 20
	self:SetText("RC Stacks: "..stacks)
end
	
function SwimCloth:OnGossipShow()
	local target = UnitName("target")
	if (target == L["Raedon Duskstriker"]
	or	target == L["Clavicus Knavingham"]
	or	target == L["Bubulo Acerbus"]
	or	target == L["Mistina Steelshield"]
	or	target == L["Dugiru"]) then
		if(SwimCloth:GetItemCount(L["Runecloth"]) >= 20) then 
			SelectGossipAvailableQuest(1);
		 end
	end
	if( target == L["Smith Regzar"] or target == L["Murgot Deepforge"] ) then
		-- Open Quest to Smith or Murgot
		if (self:GetItemCount(L["Armor Scraps"]) >= 20) then
			SelectGossipAvailableQuest(1);
		end

	elseif( target == L["Primalist Thurloga"]) then
		local anzl = self:GetItemCount(L["Stormpike Soldier's Blood"]);
		if (anzl >= 5) then		SelectGossipAvailableQuest(2);
		elseif (anzl > 0) then		SelectGossipAvailableQuest(1);
		end

	elseif( target == L["Arch Druid Renferal"]) then
		local anzl = self:GetItemCount(L["Storm Crystal"]);
		if (anzl >= 5) then		SelectGossipAvailableQuest(2);
		elseif (anzl > 0) then		SelectGossipAvailableQuest(1);
		end

	elseif( target == L["Stormpike Ram Rider Commander"]) then	-- Ram Riders
		if (self:GetItemCount(L["Frostwolf Hide"]) > 0) then
			SelectGossipAvailableQuest(1);
		end

	elseif( target == L["Frostwolf Wolf Rider Commander"]) then	-- Wolf Riders
		if (self:GetItemCount(L["Alterac Ram Hide"]) > 0) then
			SelectGossipAvailableQuest(1);
		end
	end
end
function SwimCloth:OnQuestProgress()

	local target = UnitName("target");
	if (target == L["Raedon Duskstriker"]
	or	target == L["Clavicus Knavingham"]
	or	target == L["Bubulo Acerbus"]
	or	target == L["Mistina Steelshield"]
	or	target == L["Dugiru"]) then
		if(SwimCloth:GetItemCount(L["Runecloth"]) < 20) then
		 	return
		 end
		--self:Print ("I get to progress!")
		CompleteQuest()
		--self:Print("Called Complete")
	end
	if (target == L["Wing Commander Jeztor"]
	   and self:GetItemCount(L["Stormpike Lieutenant's Flesh"]) == 0) then		return;

	elseif (target == WINGCOMMANDERGUSE
	   and self:GetItemCount(L["Stormpike Soldier's Flesh"]) == 0) then		return;

	elseif (target == L["Wing Commander Mulverick"]
	   and self:GetItemCount(L["Stormpike Commander's Flesh"]) == 0) then		return;

	elseif (target == L["Wing Commander Vipore"]
	   and self:GetItemCount(L["Frostwolf Lieutenant's Medal"]) == 0) then		return;

	elseif (target == L["Wing Commander Slidore"]
	   and self:GetItemCount(L["Frostwolf Soldier's Medal"]) == 0) then		return;

	elseif (target == L["Wing Commander Ichman"]
	   and self:GetItemCount(L["Frostwolf Commander's Medal"]) == 0) then		return;
	
   	elseif (GetZoneText() == L["Alterac Valley"] or SwimCloth.db.profile.quickquest) then
		CompleteQuest();
	end
end
function SwimCloth:OnQuestComplete()
--	self:Print("test")
	local target = UnitName("target");
	
	if (target == L["Raedon Duskstriker"]
	or	target == L["Clavicus Knavingham"]
	or	target == L["Bubulo Acerbus"]
	or	target == L["Mistina Steelshield"]
	or	target == L["Dugiru"]) then
--		self:Print("Trying to complete!")
		if(GetNumQuestChoices() == 0) then
			GetQuestReward(QuestFrameRewardPanel.itemChoice);
		end
		local runeammount = SwimCloth:GetItemCount(L["Runecloth"])
		stacks = runeammount / 20
			--SwimCloth:Print(stacks, " stacks.")
		self:Print("You have ".. stacks-1 .. " stacks left.")
	end
	if (target == L["Smith Regzar"]
	or  target == L["Wing Commander Jeztor"]
	or	target == L["Wing Commander Guse"]
	or	target == L["Wing Commander Mulverick"]
	or  target == L["Wing Commander Vipore"]
	or  target == L["Wing Commander Slidore"]
	or  target == L["Wing Commander Ichman"]
	or  target == L["Arch Druid Renferal"] 
	or	target == L["Primalist Thurloga"]
	or	target == L["Murgot Deepforge"]
	or	target == L["Stormpike Ram Rider Commander"]
	or	target == L["Frostwolf Wolf Rider Commander"]) then
		GetQuestReward(0);
	end
end

function SwimCloth:GetItemName(bag, slot)
	local itemlink;
	if (bag == -1) then	itemlink = GetInventoryItemLink("player",  slot);
	else			itemlink = GetContainerItemLink(bag,  slot);
	end
	if (itemlink) then
		local _,  _,  name = string.find(itemlink,  "^.*%[(.*)%].*$");
		return name;
	else	return "";
	end
end

function SwimCloth:GetItemCount(ItemName)
	local anzl, bagNr, bagSlot = 0
	for bagNr = 0, 10, 1 do
		for bagSlot = 1, GetContainerNumSlots(bagNr), 1 do
			if (SwimCloth:GetItemName(bagNr, bagSlot) == ItemName) then
				local _, itemCount = GetContainerItemInfo(bagNr, bagSlot)
				anzl = anzl+itemCount;
			end
		end
	end
	return anzl;
end

--Auto BG joining
function SwimCloth:sendMessage()
	if (IsRaidLeader()) then
		SendAddonMessage("SwimCloth","joinav "..SwimCloth.db.profile.avnumber,"RAID")
		self:Print(L["Joining the Raid!"])
	else
		self:Print(L["You must be the raid leader"])
	end
end

function SwimCloth:OnMsgRsv(prefix,msg,dist,sender)
	if (prefix == "SwimCloth")then
		if (strfind(msg,'joinav ')) then
			--self:Print("Joined, "..msg..", "..dist..", "..sender)
			avnum = tonumber(strsub(msg,8))
			JoinBattlefield(avnum)
			SendAddonMessage("SwimCloth","joined","RAID")
		elseif (msg == "joined") then
			if (IsRaidLeader()) then
				self:Print(sender.. " is Queued.")
			end
		elseif (msg == 'whatversion') then
			
			SendAddonMessage("SwimCloth","version "..VERSION, "RAID")
		elseif (strfind(msg,'version ')) then
			if (IsRaidLeader()) then
				self:Print(sender.." is at version: "..strsub(msg,9))
			end
		end
	end
end
